package com.feiyi.app.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.feiyi.app.R;
import com.feiyi.app.app.AppConstant;
import com.feiyi.app.base.BaseActivity;
import com.feiyi.app.bean.ArticleBean;
import com.feiyi.app.net.HttpMethods;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * 作者 : wlt
 * 创建时间:  2018-07-17
 * QQ : 1346947404
 * 邮箱:wanglt_android@163.com
 * 类说明:文章详情界面
 * In me the tiger sniffs the rose
 */

public class ArticleDetailActivity extends BaseActivity {

    @BindView(R.id.back)
    ImageView back;

    @BindView(R.id.tv_article_title)
    TextView title;

    @BindView(R.id.wv_article)
    WebView webView;
    /**
     * 文章id
     */
    private String article_id;
    /**
     * 文章标题
     */
    private String articleTitle;
    /**
     * 文章详情内容
     */
    private String data;

    private static final String TAG = "ArticleDetailActivity";

    private WebSettings webSettings;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_detail);
        ButterKnife.bind(this);
        getArticleId();
        initData();

    }

    private void getArticleId() {
        Intent intent = getIntent();
        article_id = intent.getStringExtra("article_id");
    }

    private void initData() {
        FormBody.Builder builder = new FormBody.Builder();
        if (null != article_id)
        builder.add("article_id",article_id);

        RequestBody body = builder.build();
        HttpMethods.getInstance().info.getArticle(AppConstant.ARTICLE_DETAIL,body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ArticleBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(ArticleBean articleBean) {
                        Log.e(TAG, "onNext: "+articleBean.toString() );
                        if (null != articleBean.getData()){
                            if (null != articleBean.getData().getTitle())
                                articleTitle = articleBean.getData().getTitle();
                            if (null != articleBean.getData().getHtml())
                                data = articleBean.getData().getHtml();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "获取文章详情失败 "+e.toString() );
                    }

                    @Override
                    public void onComplete() {
                        title.setText(articleTitle);
                        setWebView();
                    }
                });

    }

    private void setWebView(){
        if (webView != null) {

            webView.setHorizontalScrollBarEnabled(false);//去掉横向滚动条
            webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setSupportZoom(true);
            webSettings.setDomStorageEnabled(true);
            webSettings.setDefaultTextEncodingName("UTF-8");
            webSettings.setBuiltInZoomControls(true);
            webSettings.setDisplayZoomControls(false);


            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
            webSettings.setUseWideViewPort(true);//设置webview推荐使用的窗口
            webSettings.setLoadWithOverviewMode(true);//设置webview加载的页面的模式

            /**
             * 用WebView显示图片，可使用这个参数 设置网页布局类型：
             * 1、LayoutAlgorithm.NARROW_COLUMNS ：适应内容大小
             * 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放
             */
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
            webView.loadData(data,"text/html; charset=UTF-8", null);
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);

                }

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);

                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    webView.loadUrl(url);
                    return true;
                }
            });
        }
    }


    @OnClick(R.id.back)
    public void onClick(View view){
        if (view.getId() == R.id.back){
            if (webView.canGoBack()) {
                webView.goBack();
            }else {
                finish();
            }
        }
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dispose();
        webView = null;
    }
}
